#include "seatparameterdialog.h"
#include <QColorDialog>
#include <QStandardItemModel>
#include "ui_seatparameterdialog.h"

SeatParameterDialog::SeatParameterDialog(SeatDetectionParameter &sdp, QWidget *parent)
    : QDialog(parent)
    , seatDetectionParameter(sdp)
    , ui(new Ui::SeatParameterDialog)
{
    ui->setupUi(this);
    theSeatDetectionParameter = seatDetectionParameter;

    InitSelectedImages();

    ShowParamter();

    //connect(ui->listWidgetCameras,&QListWidget::itemSelectionChanged,this,&SeatParameterDialog::ItemSelectionChanged);
    connect(ui->listWidgetCameras,
            &QListWidget::currentItemChanged,
            this,
            &SeatParameterDialog::on_item_changed);

    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SeatParameterDialog::Accept);
}

SeatParameterDialog::~SeatParameterDialog()
{
    for(int i = 0; i < seatDetectionParameter.GetDetectionTotalSubImageCount();i++){
        delete m_ppSelectedImage[i];
    }
    delete m_ppSelectedImage;

    delete ui;
}

void SeatParameterDialog::InitSelectedImages(){

}
/**
 * @brief SeatParameterDialog::ShowParamter
 * 显示参数内容
 */
void SeatParameterDialog::ShowParamter()
{
    /// 读取基本参数
    ui->lineEditOriginalImagePath->setText(theSeatDetectionParameter.GetOriginalImagePath());
    ui->lineEditTemporalImagePath->setText(theSeatDetectionParameter.GetTemporalImagePath());
    ui->lineEditDescriptionFilePath->setText(theSeatDetectionParameter.getDescriptionFilePath());
    ui->lineEditImageFileExtension->setText(theSeatDetectionParameter.getImageFileExtension());
    ui->lineEditResultTxtPath->setText(theSeatDetectionParameter.GetResultTxtPath());
    ui->lineEditRecognitionServerIp->setText(theSeatDetectionParameter.GetRecognitionServerIp());
    ui->lineEditRecognitionServerPort->setText(theSeatDetectionParameter.GetRecognitionServerPort());
    ui->lineEditControlServerIp->setText(theSeatDetectionParameter.GetControlServerIp());
    ui->lineEditControlServerPort->setText(theSeatDetectionParameter.GetControlServerPort());

    ui->spinBoxSubImageTotal->setValue(theSeatDetectionParameter.GetDetectionTotalSubImageCount());
    ui->spinBoxSubImageRow->setValue(theSeatDetectionParameter.GetDetectionRowSubImageCount());
    ui->spinBoxSubImageColumn->setValue(theSeatDetectionParameter.GetDetectionColumnSubImageCount());
    /////////////////////////////////////////////////////////////////////////////////////////
    /// 读取相机参数
    QList<CAMERA> cameras = theSeatDetectionParameter.GetCameras();
    ui->listWidgetCameras->clear();
    foreach (CAMERA camera, cameras) {
        ui->listWidgetCameras->addItem(camera.name);
    }

    if (cameras.size() > 0) {
        QListWidgetItem *item = ui->listWidgetCameras->item(0);
        ui->listWidgetCameras->setCurrentItem(item);
        ui->listWidgetCameras->setFocus();

        CAMERA camera = cameras.at(0);
        ui->lineEditCameraName->setText(camera.name);
        ui->lineEditCameraIP->setText(camera.IP);
        ui->lineEditCameraMAC->setText(camera.MAC);
        ui->lineEditNumbers->setText(camera.numbers.join(","));
    }
    /////////////////////////////////////////////////////////////////////////////////////////
    /// 读取类别参数
    ///
    QStringList headerList;
    headerList << QString::fromUtf8("类别") << QString::fromUtf8("编号");

    ui->tableWidgetClasses->setColumnCount(headerList.size());
    ui->tableWidgetClasses->setHorizontalHeaderLabels(headerList);
    ui->tableWidgetClasses->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidgetClasses->horizontalHeader()->setStyleSheet(
        "QHeaderView::section{background:skyblue;color:black;}");
    ui->tableWidgetClasses->setStyleSheet("QTableWidget { border: 1px solid black; }");
    ui->tableWidgetClasses->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidgetClasses->setSelectionMode(QAbstractItemView::SingleSelection);
    QHeaderView *headerView = ui->tableWidgetClasses->verticalHeader();
    headerView->setHidden(true);

    QMap<QString, int> &classes = theSeatDetectionParameter.GetClasses();

    QList<QString> keys = classes.keys();
    foreach (QString key, keys) {
        int value = classes[key];

        QStringList dataList;
        dataList << key << QString::number(value);
        //获取表格中数据的条数，作为新插入的行号
        int row = ui->tableWidgetClasses->rowCount();
        //从表格最后新增一行
        ui->tableWidgetClasses->insertRow(row);

        QTableWidgetItem *pItemKey = new QTableWidgetItem(dataList[0]);
        ui->tableWidgetClasses->setItem(row, 0, pItemKey);

        QTableWidgetItem *pItemValue = new QTableWidgetItem(dataList[1]);
        ui->tableWidgetClasses->setItem(row, 1, pItemValue);
    }

    /////////////////////////////////////////////////////////
    headerList.clear();
    headerList << QString::fromUtf8("图像编号") << QString::fromUtf8("旋转角度") << QString::fromUtf8("缩放系数")
        << QString::fromUtf8("平移位置") << QString::fromUtf8("凹陷检测");

    ui->tableWidgetSubImages->setColumnCount(headerList.size());
    ui->tableWidgetSubImages->setHorizontalHeaderLabels(headerList);
    ui->tableWidgetSubImages->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidgetSubImages->horizontalHeader()->setStyleSheet(
        "QHeaderView::section{background:skyblue;color:black;}");
    ui->tableWidgetSubImages->setStyleSheet("QTableWidget { border: 1px solid black; }");
    ui->tableWidgetSubImages->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidgetSubImages->setSelectionMode(QAbstractItemView::SingleSelection);
    headerView = ui->tableWidgetSubImages->verticalHeader();
    headerView->setHidden(true);

    /////////////////////////////////////////////////////////////////////////////////////////
    /// 读取3D座椅的参数，angle,scale,viewpos;凹陷检测参数
    ///
    QStringList selectedImage = seatDetectionParameter.GetCollapseSurface();
    QList<SEATSHOWINFO> seatshowinfos = theSeatDetectionParameter.GetSeatShowInfos();
    int index = 0;
    foreach (SEATSHOWINFO ssi, seatshowinfos) {
        //获取表格中数据的条数，作为新插入的行号
        int row = ui->tableWidgetSubImages->rowCount();
        //从表格最后新增一行
        ui->tableWidgetSubImages->insertRow(row);

        QTableWidgetItem *pItemNumber = new QTableWidgetItem(QString("%1").arg(index));
        ui->tableWidgetSubImages->setItem(row, 0, pItemNumber);

        QTableWidgetItem *pItemAngle = new QTableWidgetItem(QString("%1,%2,%3").arg(ssi.angle.x()).arg(ssi.angle.y()).arg(ssi.angle.z()));
        ui->tableWidgetSubImages->setItem(row, 1, pItemAngle);

        QTableWidgetItem *pItemScale = new QTableWidgetItem(QString("%1,%2,%3").arg(ssi.scale.x()).arg(ssi.scale.y()).arg(ssi.scale.z()));
        ui->tableWidgetSubImages->setItem(row, 2, pItemScale);

        QTableWidgetItem *pItemViewpos = new QTableWidgetItem(QString("%1,%2,%3").arg(ssi.viewpos.x()).arg(ssi.viewpos.y()).arg(ssi.viewpos.z()));
        ui->tableWidgetSubImages->setItem(row, 3, pItemViewpos);

        QTableWidgetItem *checkBox = new QTableWidgetItem();
        checkBox->setCheckState(Qt::Unchecked);
        for(int j = 0; j < selectedImage.size();j++){
            if(index == selectedImage.at(j).toInt()){
                checkBox->setCheckState(Qt::Checked);
                break;
            }
        }
        if(index != 0){
            ui->tableWidgetSubImages->setItem(row, 4, checkBox);
        }


        index++;
    }
}

/**
 * @brief SeatParameterDialog::ItemSelectionChanged
 * 暂时没有使用
 */
void SeatParameterDialog::ItemSelectionChanged()
{
    QModelIndex index = ui->listWidgetCameras->currentIndex();
    CAMERA camera = theSeatDetectionParameter.GetCameras().at(index.row());
    ui->lineEditCameraName->setText(camera.name);
    ui->lineEditCameraIP->setText(camera.IP);
    ui->lineEditCameraMAC->setText(camera.MAC);
    ui->lineEditNumbers->setText(camera.numbers.join(","));

    //QMessageBox::information(this,"TiShi","ItemSelectionChanged" );
}

void SeatParameterDialog::on_pushButtonAddCamera_clicked()
{
    CAMERA camera;
    pNewCameraDialog = new NewCameraDialog(camera, this);
    if (pNewCameraDialog->exec() == QDialog::Accepted) {
        theSeatDetectionParameter.SetCameraCount(theSeatDetectionParameter.GetCameraCount() + 1);
        theSeatDetectionParameter.GetCameras().append(camera);

        ShowParamter();
    } else {
    }
}

void SeatParameterDialog::on_pushButtonDelCamera_clicked()
{
    //QModelIndex index = ui->listWidgetCameras->currentIndex();
    //ui->listWidgetCameras->removeItemWidget(ui->listWidgetCameras->currentItem());

    //theSeatDetectionParameter.GetCameras().removeAt(index.row());
    //theSeatDetectionParameter.SetCameraCount(theSeatDetectionParameter.GetCameraCount() - 1);

    //ShowParamter();

    QModelIndex index = ui->listWidgetCameras->currentIndex();
    QListWidgetItem *item = ui->listWidgetCameras->currentItem();

    //theSeatDetectionParameter.GetCameras().removeAt(index.row());
    //theSeatDetectionParameter.SetCameraCount(theSeatDetectionParameter.GetCameraCount() - 1);
    delete item;

    QList<CAMERA> &cameras = theSeatDetectionParameter.GetCameras();
    cameras.removeAt(index.row());
    theSeatDetectionParameter.SetCameraCount(cameras.size());
}

QVector3D convertFromText(QString text){
    QStringList xyz = text.split(",");
    return QVector3D(xyz[0].toFloat(),xyz[1].toFloat(),xyz[2].toFloat());
}

void SeatParameterDialog::Accept()
{
    /// 读取基本参数
    /// 此段代码，是为了保存默认第一行元素的值
    QModelIndex index = ui->listWidgetCameras->currentIndex();
    if (index.row() >= 0) {
        QList<CAMERA> &cameras = theSeatDetectionParameter.GetCameras();

        CAMERA theCamera;
        theCamera.name = ui->lineEditCameraName->text();
        theCamera.MAC = ui->lineEditCameraMAC->text();
        theCamera.IP = ui->lineEditCameraIP->text();
        theCamera.numbers = ui->lineEditNumbers->text().split(",");

        cameras.replace(index.row(), theCamera);
    }

    /// 使用此类属性成员theSeatDetectionParameter修改MainWindow（通过引用）成员seatDetectionParameter的内容
    seatDetectionParameter = theSeatDetectionParameter;
    /// 修改MainWindow（通过引用）成员seatDetectionParameter的内容
    seatDetectionParameter.SetOriginalImagePath(ui->lineEditOriginalImagePath->text());
    seatDetectionParameter.SetTemporalImagePath(ui->lineEditTemporalImagePath->text());
    seatDetectionParameter.SetDescriptionFilePath(ui->lineEditDescriptionFilePath->text());
    seatDetectionParameter.SetImageFileExtension(ui->lineEditImageFileExtension->text());
    seatDetectionParameter.SetResultTxtPath(ui->lineEditResultTxtPath->text());
    seatDetectionParameter.SetRecognitionServerIp(ui->lineEditRecognitionServerIp->text());
    seatDetectionParameter.SetRecognitionServerPort(ui->lineEditRecognitionServerPort->text());
    seatDetectionParameter.SetControlServerIp(ui->lineEditControlServerIp->text());
    seatDetectionParameter.SetControlServerPort(ui->lineEditControlServerPort->text());

    seatDetectionParameter.SetDetectionTotalSubImageCount(ui->spinBoxSubImageTotal->value());
    seatDetectionParameter.SetDetectionRowSubImageCount(ui->spinBoxSubImageRow->value());
    seatDetectionParameter.SetDetectionColumnSubImageCount(ui->spinBoxSubImageColumn->value());

    /// 保存ClassesTable中的数据
    int rows = ui->tableWidgetClasses->rowCount();
    int cols = ui->tableWidgetClasses->columnCount();
    QMap<QString, int> map;
    for (int i = 0; i < rows; i++) {
        QString key = ui->tableWidgetClasses->item(i, 0)->text();
        QString value = ui->tableWidgetClasses->item(i, 1)->text();
        map.insert(key, value.toInt());
    }
    seatDetectionParameter.SetClasses(map);
    // 保存 检查塌陷图像的信息
    /*QStringList selectedImages;
    for(int i = 0; i < seatDetectionParameter.GetDetectionTotalSubImageCount();i++){
        if(m_ppSelectedImage[i]->isChecked()){
            selectedImages << QString("%1").arg(i);
        }
    }
    seatDetectionParameter.SetCollapseSurface(selectedImages);*/
    // 保存 3D座椅的参数，angle,scale,viewpos;凹陷检测参数
    int countItem = ui->tableWidgetSubImages->rowCount();
    QStringList selectedImages;
    QList<SEATSHOWINFO>& ssis = seatDetectionParameter.GetSeatShowInfos();
    ssis.resize(countItem);
    for(int i = 0;i < countItem; i++){
        QString angleText = ui->tableWidgetSubImages->item(i, 1)->text();
        ssis[i].angle = convertFromText(angleText);
        QString scaleText = ui->tableWidgetSubImages->item(i, 2)->text();
        ssis[i].scale = convertFromText(scaleText);
        QString viewposText = ui->tableWidgetSubImages->item(i, 3)->text();
        ssis[i].viewpos = convertFromText(viewposText);
        if(i > 0){
            if(ui->tableWidgetSubImages->item(i, 4)->checkState() == Qt::Checked){ //选中
                selectedImages << QString("%1").arg(i);
            }
        }
    }
    seatDetectionParameter.SetCollapseSurface(selectedImages);
}

void SeatParameterDialog::on_item_changed(QListWidgetItem *current, QListWidgetItem *previous)
{
    /// 修改选择改变前一个Item的属性，并保存到此类属性成员theSeatDetectionParameter中
    int indexPrevious = ui->listWidgetCameras->row(previous);
    if (indexPrevious >= 0) {
        QList<CAMERA> &cameras = theSeatDetectionParameter.GetCameras();
        qDebug() << indexPrevious << ui->lineEditCameraName->text();
        CAMERA theCamera;
        theCamera.name = ui->lineEditCameraName->text();
        theCamera.MAC = ui->lineEditCameraMAC->text();
        theCamera.IP = ui->lineEditCameraIP->text();
        theCamera.numbers = ui->lineEditNumbers->text().split(",");

        cameras.replace(indexPrevious, theCamera);
    }
    /// 显示当前选中Item的内容
    int indexCurrent = ui->listWidgetCameras->row(current);
    if (indexCurrent >= 0) {
        CAMERA camera = theSeatDetectionParameter.GetCameras().at(indexCurrent);
        ui->lineEditCameraName->setText(camera.name);
        ui->lineEditCameraIP->setText(camera.IP);
        ui->lineEditCameraMAC->setText(camera.MAC);
        ui->lineEditNumbers->setText(camera.numbers.join(","));
    }
}

void SeatParameterDialog::on_pushButtonAddClass_clicked()
{
    int row = ui->tableWidgetClasses->rowCount();
    //从表格最后新增一行
    ui->tableWidgetClasses->insertRow(row);

    QTableWidgetItem *pItemKey = new QTableWidgetItem("--");
    ui->tableWidgetClasses->setItem(row, 0, pItemKey);

    QTableWidgetItem *pItemValue = new QTableWidgetItem("--");
    ui->tableWidgetClasses->setItem(row, 1, pItemValue);
}

void SeatParameterDialog::on_pushButtonDelClass_clicked()
{
    int indexRow = ui->tableWidgetClasses->currentRow();
    if (indexRow >= 0) {
        ui->tableWidgetClasses->removeRow(indexRow);
    }
}

